define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'sale_order/index' + location.search,
                    add_url: 'sale_order/add',
                    edit_url: 'sale_order/edit',
                    del_url: 'sale_order/del',
                    table: 'sale_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'order_date', title: __('Order_date'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'manufacturer.name', title: __('Manufacturer'), operate: 'LIKE'},
                        {field: 'customer.name', title: __('Customer'), operate: 'LIKE'},
                        {field: 'total_amount', title: __('Total_amount'), operate: 'BETWEEN', sortable: true},
                        {field: 'total_weight', title: __('Total_weight'), operate: 'BETWEEN', sortable: true},
                        {field: 'discount_amount', title: __('Discount_amount'), operate: 'BETWEEN'},
                        {field: 'total_purchase_price', title: __('Total_purchase_price'), operate: 'BETWEEN'},
                        {field: 'customer_payment', title: __('Customer_payment'), operate: 'BETWEEN'},
                        {field: 'manufacturer_payment', title: __('Manufacturer_payment'), operate: 'BETWEEN'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // 商品行模板索引
            var itemIndex = 0;
            
            // 初始化页面
            $(document).ready(function() {
                // 隐藏模板行
                $('#item-template').hide();
                
                // 添加第一行商品
                addItem();
                
                // 绑定添加商品按钮事件
                $('.btn-add-item').click(function() {
                    addItem();
                });
                
                // 绑定删除商品按钮事件 (使用事件委托)
                $('#item-list').on('click', '.btn-remove-item', function() {
                    // 至少保留一行商品
                    if ($('.item-row:visible').length > 1) {
                        $(this).closest('tr').remove();
                        calculateTotals();
                    } else {
                        Toastr.error('至少需要一个商品项');
                    }
                });
                
                // 绑定价格和数量变化事件
                $('#item-list').on('change', '.item-unit-price, .item-quantity', function() {
                    calculateSubtotal(this);
                });
                
                // 绑定优惠金额变化事件
                $('#c-discount_amount').on('change', function() {
                    calculateTotalAmount();
                });
            });
            
            // 添加商品行
            function addItem() {
                // 克隆模板行
                var newRow = $('#item-template').clone();
                newRow.removeAttr('id').show();
                
                // 更新索引
                updateRowIndex(newRow, itemIndex++);
                
                // 添加到列表
                $('#item-list').append(newRow);
                
                // 初始化新行的selectpage
                newRow.find('.product-select').each(function() {
                    $(this).selectPage({
                        eAjaxSuccess: function(data) {
                            return data;
                        },
                        eSelect: function(data) {
                            if (data && data.id) {
                                var row = $(this.input).closest('tr');
                                
                                // 通过AJAX获取商品详细信息
                                $.ajax({
                                    url: 'product/index',
                                    type: 'get',
                                    dataType: 'json',
                                    data: {
                                        ids: data.id
                                    },
                                    success: function(res) {
                                        if (res && res.rows && res.rows.length > 0) {
                                            var product = res.rows[0];
                                            
                                            // 自动填充商品信息
                                            row.find('.item-unit-price').val(product.unit_price);
                                            row.find('.item-jin-per-bag').val(product.jin_per_bag);
                                            row.find('.item-bags-per-piece').val(product.bags_per_piece);
                                            row.find('.item-purchase-price').val(product.unit_price * 0.8); // 默认进货价为单价的80%
                                            
                                            // 重新计算小计和总计
                                            calculateSubtotal(row.find('.item-unit-price')[0]);
                                        }
                                    }
                                });
                            }
                        }
                    });
                });
            }
            
            // 更新行索引
            function updateRowIndex(row, index) {
                row.find('input').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        $(this).attr('name', name.replace('__index__', index));
                    }
                });
            }
            
            // 计算小计
            function calculateSubtotal(element) {
                var row = $(element).closest('tr');
                var unitPrice = parseFloat(row.find('.item-unit-price').val()) || 0;
                var quantity = parseInt(row.find('.item-quantity').val()) || 0;
                var subtotal = unitPrice * quantity;
                
                // 更新小计显示
                row.find('.item-subtotal').text(subtotal.toFixed(2));
                
                // 重新计算总计
                calculateTotals();
            }
            
            // 计算所有总计
            function calculateTotals() {
                var totalAmount = 0;
                var totalWeight = 0;
                var totalPurchasePrice = 0;
                
                // 遍历所有商品行
                $('.item-row:visible').each(function() {
                    var unitPrice = parseFloat($(this).find('.item-unit-price').val()) || 0;
                    var quantity = parseInt($(this).find('.item-quantity').val()) || 0;
                    var jinPerBag = parseFloat($(this).find('.item-jin-per-bag').val()) || 0;
                    var bagsPerPiece = parseFloat($(this).find('.item-bags-per-piece').val()) || 0;
                    var purchasePrice = parseFloat($(this).find('.item-purchase-price').val()) || 0;
                    
                    // 计算商品总金额
                    totalAmount += unitPrice * quantity;
                    
                    // 计算商品总重量
                    totalWeight += jinPerBag * bagsPerPiece * quantity;
                    
                    // 计算总进货价
                    totalPurchasePrice += purchasePrice * quantity;
                });
                
                // 更新总金额和总重量显示
                $('#c-total_weight').val(totalWeight.toFixed(2));
                
                // 应用优惠金额
                calculateTotalAmount();
                
                // 更新总进货价
                $('#c-total_purchase_price').val(totalPurchasePrice.toFixed(2));
            }
            
            // 计算总金额（应用优惠）
            function calculateTotalAmount() {
                var totalAmount = 0;
                
                // 计算商品总金额
                $('.item-row:visible').each(function() {
                    var unitPrice = parseFloat($(this).find('.item-unit-price').val()) || 0;
                    var quantity = parseInt($(this).find('.item-quantity').val()) || 0;
                    totalAmount += unitPrice * quantity;
                });
                
                // 应用优惠金额
                var discountAmount = parseFloat($('#c-discount_amount').val()) || 0;
                totalAmount = Math.max(0, totalAmount - discountAmount);
                
                // 更新总金额
                $('#c-total_amount').val(totalAmount.toFixed(2));
            }
            
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
}); 